package net.widevision.android;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import twitter4j.IDs;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.http.AccessToken;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;

public class TwitterApp 
{
	
	public static final String CALLBACK_URL = "twitterapp://connect";
	
	private static final String TAG = "TwitterApp";
	
	private Twitter mTwitter;
	
	private User user;
	
	private TwitterSession mSession;
	
	private AccessToken mAccessToken;
	
	private CommonsHttpOAuthConsumer mHttpOauthConsumer;
	
	private OAuthProvider mHttpOauthprovider;
	
	public InputStream is;
	
	private String mConsumerKey;
	
	private String mSecretKey;
	
    private ProgressDialog mProgressDlg;
	
	private TwDialogListener mListener;
	
	private Context context;
	
	private boolean mInit = true;
	
	int followerscount,followingcount;

	IDs friendsids,followerids;
	
	int ids[];
	
	boolean isfriend;
	
	String locatinstr,UserName,ScreenName,Tweet,TweetName,TweetScreenName,description;

	Status Text;
	
	Paging paging = new Paging(1, 20);
	
	ResponseList<twitter4j.Status> HomeTweetText,UserTweetText,RetweetedText;
	
	ResponseList<twitter4j.User> frndlisttext,followerlisttext;
		
	ArrayList<String> twetlist,homeTimelineNamelist;

	public TwitterApp(Context context, String consumerKey, String secretKey)
	{
		this.context	= context;
		
		mTwitter 		= new TwitterFactory().getInstance();
		mSession		= new TwitterSession(context);
		mProgressDlg	= new ProgressDialog(context);
		
		mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		mConsumerKey 	= "JXmXcE5yFPLIRCCtQ79eg";
		mSecretKey	 	= "dnVojAwaewvEt8E2QwLYtavwm8cdUHwph7lZCaQPMY";
	
		mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
		mHttpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
													 "http://twitter.com/oauth/access_token",
													 "http://twitter.com/oauth/authorize");
		mAccessToken	= mSession.getAccessToken();
		configureToken();
	
	}
	
	public void setListener(TwDialogListener listener)
	{
		mListener = listener;
	}
	
	@SuppressWarnings("deprecation")
	private void configureToken() 
	{
		if (mAccessToken != null)
		{
			if (mInit)
			{
				mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
				mInit = false;
			}
			mTwitter.setOAuthAccessToken(mAccessToken);
		}
	}
	
	public boolean hasAccessToken()
	{
		return (mAccessToken == null) ? false : true;
	}
	
	public void resetAccessToken()
	{
		if (mAccessToken != null) 
		{
			mSession.resetAccessToken();
		
			mAccessToken = null;
		}
	}
	
	public String getUsername()
	{
		return mSession.getUsername();
	}
	
	public String getScreenName()
	{
		try
		{
			ScreenName=mTwitter.getScreenName();
		}
		catch (TwitterException e) 
		{
			e.printStackTrace();
		}
		return ScreenName;
	}
	
	public int getId() throws IllegalStateException, TwitterException
	{
		int id=mTwitter.getId();
		return id;
	}
	
	public boolean existsFriendship(String userA,String userB)
	{
	   try 
	   {
		   isfriend = mTwitter.existsFriendship(userA, userB);
	   }
	   catch (TwitterException e)
	   {
			e.printStackTrace();
	   }
	   return isfriend;
	}
	
	public User showUser(int userId)
	{
		try
		{
			user=mTwitter.showUser(userId);
		} 
		catch (TwitterException e)
		{
			e.printStackTrace();
		}
		return user;
	}
	
	public User destroyFriendship(String screenName)
	{
		try 
		{
			user=mTwitter.destroyFriendship(screenName);
		   
		}
		catch (TwitterException e)
		{
			e.printStackTrace();
		}
		return user;
	}
	public User createFriendship(String screenName)
	{
		try
		{
			user=mTwitter.createFriendship(screenName);
		} 
		catch (TwitterException e)
		{
			e.printStackTrace();
		}
		return user;
	}
	public ResponseList<User> Friendsids(int id) 
	{
		try 
		{
			friendsids=mTwitter.getFriendsIDs(id);
			
			int idarray[]=friendsids.getIDs();
			
			int arraylen=idarray.length;
			
			for(int i=0;i<=arraylen;i++)
			{
				frndlisttext=mTwitter.lookupUsers(idarray);
			}
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return frndlisttext;
	}
	
	public ResponseList<User> Followerids(int id) {
		try {
			
			followerids=mTwitter.getFollowersIDs(id);
			
			int idarray[]=followerids.getIDs();
			
			int arraylen=idarray.length;
			
			for(int i=0;i<=arraylen;i++)
			{
				followerlisttext=mTwitter.lookupUsers(idarray);
			}
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return followerlisttext;
	}
	
	public  ResponseList<Status> getUserTimeLine() {
		try {
			UserTweetText=mTwitter.getUserTimeline();
			} catch (TwitterException e) {
			
				e.printStackTrace();
			}
			return UserTweetText;
	    }
	
	public ResponseList<Status> getRetweetedByMe(){
		
		try {
			RetweetedText=mTwitter.getRetweetedToMe();
			
			} catch (TwitterException e) {
			
				e.printStackTrace();
			}
			return UserTweetText;
		
	}
	
/*	
	
	
	public String getProfilename() {
//			user=mTwitter.userName();
		    UserName=user.getName();
		    return UserName;
}
	public  ResponseList<Status> getHomeTimeLine() {
	try {
		HomeTweetText=mTwitter.getHomeTimeline(paging);
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return HomeTweetText;
    }
	
	public  ResponseList<Status> getUserTimeLine() {
		try {
				UsettweetText=mTwitter.getUserTimeline();
			} catch (TwitterException e) {
			
				e.printStackTrace();
			}
			return UsettweetText;
	    }
	
	public int followersCount() {
		try {
			user=mTwitter.followerscount();
		    followerscount=user.getFollowersCount();
			
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return followerscount;
	}
	
	public int followingsCount() {
		try {
			user=mTwitter.followingscount();
		    followingcount=user.getFriendsCount();
			
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return followingcount;
	}
	
	public String getLocation() {
		try {
			user=mTwitter.getLocation();
		    locatinstr=user.getLocation();
			
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return locatinstr;
	}
	public String getDescription() {
		try {
			user=mTwitter.getDesc();
		    description=user.getDescription();
			
		} catch (TwitterException e) {
			
			e.printStackTrace();
		}
		return description;
	}
	
	
	
	public Drawable profieImage() throws TwitterException {
			user=mTwitter.profileImage();
			URL u=user.getProfileImageURL();
			try {
				 is = u.openStream();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			Drawable d = Drawable.createFromStream(is, "src name");
			
            return d;
}
	*/
	
	public void updateStatus(String status) throws Exception
	{
		try
		{
			mTwitter.updateStatus(status);
		}
		catch (TwitterException e)
		{
			throw e;
		}
	}
	
	public void authorize() 
	{
		mProgressDlg.setMessage("Initializing ...");
		mProgressDlg.show();
		
		new Thread()
		{
			@Override
			public void run() 
			{
				String authUrl = "";
				int what = 1;
				
				try 
				{
					authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);	
					
					what = 0;
					
					Log.d(TAG, "Request token url " + authUrl);
				} catch (Exception e) {
					Log.d(TAG, "Failed to get request token");
					
					e.printStackTrace();
				}
				
				mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
			}
		}.start();
	}
	
	public void processToken(String callbackUrl)  {
		mProgressDlg.setMessage("Finalizing ...");
		mProgressDlg.show();
		
		final String verifier = getVerifier(callbackUrl);

		new Thread() {
			@Override
			public void run() {
				int what = 1;
				
				try {
					mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
		
					mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
				
					configureToken();
				
					User user = mTwitter.verifyCredentials();
				
			        mSession.storeAccessToken(mAccessToken, user.getName());
			        
			        what = 0;
				} catch (Exception e){
					Log.d(TAG, "Error getting access token");
					
					e.printStackTrace();
				}
				
				mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
			}
		}.start();
	}
	
	private String getVerifier(String callbackUrl) {
		String verifier	 = "";
		
		try {
			callbackUrl = callbackUrl.replace("twitterapp", "http");
			
			URL url 		= new URL(callbackUrl);
			String query 	= url.getQuery();
		
			String array[]	= query.split("&");

			for (String parameter : array) {
	             String v[] = parameter.split("=");
	             
	             if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
	            	 verifier = URLDecoder.decode(v[1]);
	            	 break;
	             }
	        }
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		return verifier;
	}
	
	private void showLoginDialog(String url) {
		final TwDialogListener listener = new TwDialogListener() {
			@Override
			public void onComplete(String value) {
				processToken(value);
			}
			
			@Override
			public void onError(String value) {
				mListener.onError("Failed opening authorization page");
			}
		};
		
		new TwitterDialog(context, url, listener).show();
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgressDlg.dismiss();
			
			if (msg.what == 1) {
				if (msg.arg1 == 1)
					mListener.onError("Error getting request token");
				else
					mListener.onError("Error getting access token");
			} else {
				if (msg.arg1 == 1)
					showLoginDialog((String) msg.obj);
				else
					mListener.onComplete("");
			}
		}
	};
	
	public interface TwDialogListener {
		public void onComplete(String value);		
		
		public void onError(String value);
	}
}